<template>
  <!-- :row-selection="rowSelection" -->
  <BoTable
    :columns="columns"
    :request="_request"
    row-key="contractId"
    ref="tableRef"
  >
    <template #leftContainer>
      <div class="mr-4 w-48 border-r border-[rgba(255,255,255,.3)]">
        <div class="module-title detection">关联监测阵</div>
        <Tree
          v-if="treeData.length"
          :tree-data="treeData"
          show-icon
          default-expand-all
        >
          <template #title="scope">
            <span @click="() => handleSelectStructure(scope)">{{
              scope.structureName
            }}</span>
          </template>
        </Tree>
      </div>
    </template>
  </BoTable>
  <Modal
    v-model:open="flag"
    @ok="handleOk"
    :footer="false"
    wrapClassName="view_modal"
    :destroyOnClose="true"
  >
    <triggerData
      :deviceInfo="deviceInfo"
      v-model:showWitch="showWitch"
      :fetchInfoApi="() => dataInfo"
      :data="dataInfo"
      :title="showWitch === 'trigger' ? '设备触发数据' : '数据产出'"
      :options="option"
    >
      <template #header v-if="showWitch == 'trigger'">
        <!-- <div class="custom_header">
          <div>
            <div>设备标识:</div>
            <div>{{ '--' }}</div>
          </div>
          <div>
            <div>采样率:</div>
            <div>{{ '--' }}</div>
          </div>
          <div>
            <div>仪器烈度:</div>
            <div>{{ '--' }}</div>
          </div>
        </div> -->
      </template>
    </triggerData>
  </Modal>

  <!-- 预览pdf -->
  <BoPreviewPdf
    title="预览"
    :iframe-url="iframeUrl"
    v-model:open="visible"
  ></BoPreviewPdf>

  <FormModal :columns="item">
    <template #details>
      <div class="generate_error_msg">
        {{ generateErrorMsg || '-' }}
      </div>
    </template>
  </FormModal>
  <globalLoading v-model:visible="showLoading" tip="图表生成中..." />
</template>

<route lang="json">
{
  "name": "强震测点产出",
  "meta": { "title": "强震测点产出" }
}
</route>

<script setup lang="tsx">
import { computed, provide, ref, watch } from 'vue';
import { useFormModal } from '@boeyo/hooks';
import { useDicts, useUserStore } from '@boeyo/portal';
import { download } from '@boeyo/shared';
import { BoPreviewPdf, BoTable, BoTableProps } from '@boeyo/ui';
import { Modal, Tree, message } from 'ant-design-vue';
import dayjs from 'dayjs';
import globalLoading from '@/components/globalLoading/index.vue';
import triggerData from '@/components/triggerData/index.vue';
import { getWaveInfo } from '@/utils/index';
import {
  createEventDataReport,
  downloadGenerateById,
  fetchHistoryData,
  pointEvent,
  responseSpectrum,
  signal,
  tree,
} from './api';

const userStore = useUserStore();
const license = userStore.license;
const showLoading = ref(false);
const generateErrorMsg = ref('');
const { deviceTypeEnum } = useDicts(['device_type']);
const showRows = ref();
provide(
  'rowInfo',
  computed(() => showRows.value),
);
const treeData = ref([]);

const getTreeData = async () => {
  const res = await tree({});
  treeData.value = res.data;
};
getTreeData();

const _request = (queryParams: any) => {
  queryParams.startTime = queryParams.time?.[0];
  queryParams.endTime = queryParams.time?.[1];
  return pointEvent({ ...queryParams, ...params });
};

const { FormModal, open } = useFormModal({
  size: 'middle',
  column: 1,
});

const _info = (params: any) => {
  params.id = logId.value;
  params.type = 1;
  return {
    total: 0,
    rows: [],
  };
};

const _columns = computed<BoTableProps['columns']>(() => [
  {
    title: '操作时间',
    dataIndex: 'time',
  },
]);

const columns = computed<BoTableProps['columns']>(() => [
  {
    title: '所属项目',
    dataIndex: 'projectName',
  },
  {
    title: '触发时间',
    dataIndex: 'time',
    valueType: 'dateRange',
    hideInTable: true,
  },
  {
    title: '硬件序列号',
    dataIndex: 'deviceCode',
    hideInSearch: true,
  },
  {
    title: '关联设备',
    dataIndex: 'stationId',
    hideInSearch: true,
  },
  {
    title: '软件版本',
    dataIndex: 'version',
    hideInSearch: true,
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    hideInSearch: true,
    valueType: 'select',
    valueEnum: deviceTypeEnum.value,
  },
  {
    title: '设备型号',
    dataIndex: 'model',
    hideInSearch: true,
  },
  {
    title: '开始时间',
    dataIndex: 'startTime',
    hideInSearch: true,
  },
  {
    title: '结束时间',
    dataIndex: 'endTime',
    hideInSearch: true,
  },
  {
    title: '产出数据',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    actions: [
      {
        text: '设备触发数据',
        onClick(record) {
          onDevices(record, 'trigger');
        },
      },
      {
        text: '数据产出',
        hidden: !['3', '4', '5'].some((item) =>
          (license.vipPaks as string[]).includes(item),
        ),
        onClick(record) {
          onDevices(record, 'signalNoiseRatio');
        },
      },
    ],
  },
  {
    title: '产出报告',
    dataIndex: 'operation1',
    hideInSearch: true,
    fixed: 'right',
    actions({ record }) {
      const style = {
        color: 'red',
      };
      return [
        {
          text: record.generateId ? (
            '预览'
          ) : (
            <span>
              <span style={style}>！</span>
              <span>预览</span>
            </span>
          ),
          onClick: async (record) => {
            if (!record.generateId) {
              generateErrorMsg.value = record.generateErrorMsg;
              return open({
                title: '日志',
                modalType: 'disabled',
                hideFooter: true,
                request: async (params: any) => {},
                defaultValue: record,
              });
            }

            const result = await downloadGenerateById(record.generateId, 'pdf');
            const blob = new Blob([result.data], { type: 'application/pdf' });
            const imageUrl = URL.createObjectURL(blob);
            iframeUrl.value = imageUrl;
            visible.value = true;
          },
        },
        {
          text: '重新生成',
          hidden: canRegenerate.value,
          onClick: async (record) => {
            canRegenerate.value = true;
            message.loading('报告重新生成中..', 0);
            const res = await createEventDataReport(record.id);
            message.destroy();
            if (res.code === 200) {
              message.success('报告生成完毕!');
            } else {
              message.info(res.msg);
            }
            canRegenerate.value = false;
            tableRef.value.refresh();
          },
        },
        {
          text: '下载',
          hidden: !record.generateId,
          onClick: async (record) => {
            const res = await downloadGenerateById(record.generateId, 'pdf');
            download(
              res.data as unknown as Blob,
              `data_${dayjs().format('YYYY-MM-DD HH:mm:ss')}.pdf`,
            );
          },
        },
      ];
    },
  },
]);
const logId = ref('');
const item = computed<BoFormProps['columns']>(() => [
  {
    title: '',
    dataIndex: 'details',
    valueType: 'input',
    formItemProps: {
      wrapperCol: { span: 24 },
    },
  },
]);

const iframeUrl = ref();
const canRegenerate = ref(false);
const visible = ref(false);
const selectKeys = ref<number[]>([]);
const rowSelection = computed<BoTableProps['rowSelection']>(() => {
  return {
    onChange(values) {
      selectKeys.value = values as number[];
    },
  };
});

const handleOk = () => {};
const flag = ref(false);
const dataInfo = ref({});
const queryParams = ref({});
const queryParams2 = computed(() => {
  const start = queryParams.value.startTime;
  const startTime = start
    ? dayjs(start).subtract(15, 'second').format('YYYY-MM-DD HH:mm:ss')
    : '';
  const endTime = start
    ? dayjs(start).subtract(5, 'second').format('YYYY-MM-DD HH:mm:ss')
    : '';
  return { startTime, endTime, stationIds: deviceInfo.value };
});
const onDevices = async (record, type) => {
  showWitch.value = type;
  showLoading.value = true;
  // message.loading('图表生成中..', 0);
  const { startTime, stationId, endTime } = record;
  deviceInfo.value = [stationId];
  setTimeout(async () => {
    if (type === 'trigger') {
      try {
        const { deviceInfoList, dataInfo: data } = await getWaveInfo(
          stationId,
          dayjs(startTime).add(-30, 's').format('YYYY-MM-DD HH:mm:ss'),
          endTime,
          fetchHistoryData,
        );
        option.value.deviceInfoList = deviceInfoList;
        dataInfo.value = data;
      } catch (error) {
        showLoading.value = false;
      }
    } else {
      queryParams.value = {
        stationIds: deviceInfo.value,
        startTime,
        endTime,
      };
      const signalData = await signal(queryParams.value);
      const signalData2 = await signal(queryParams2.value);
      dataInfo.value = {
        result1: signalData.data,
        result2: signalData2.data,
      };
      init(signalData.data);
    }
    showLoading.value = false;
    flag.value = true;
  }, 300);
};

const deviceInfo = ref([]);

const option: any = ref({});
const showWitch = ref();

let params: Record<string, any> = {};
const tableRef = ref();
const handleSelectStructure = (scope) => {
  if (!scope) return;
  const { monitoringType, id } = scope;
  params = {};
  switch (monitoringType) {
    case '1':
      params.netId = id;
      break;
    case '2':
      params.regionId = id;
      break;
    case '3':
      params.structureId = id;
      break;
  }
  tableRef.value.search();
};

const init = (data) => {
  message.destroy();
  if (!Object.keys(data).length) {
    message.info('暂无数据!');
  }

  const resultList = Object.keys(data);
  option.value.deviceInfoList = deviceInfo.value.map((i) => {
    return {
      label: i,
      value: i,
      disabled: !resultList.includes(i.replaceAll('.', '')),
    };
  });
};

watch(
  () => showWitch.value,
  async (val) => {
    if (val === 'signalNoiseRatio') {
      if (!flag.value) return;
      const signalData = await signal(queryParams.value);
      const signalData2 = await signal(queryParams2.value);
      dataInfo.value = {
        result1: signalData.data,
        result2: signalData2.data,
      };
    } else if (val === 'waveform') {
      const signalData = await signal(queryParams.value);
      dataInfo.value = signalData.data;
      init(signalData.data);
    } else if (val === 'spectrum') {
      const signalData = await responseSpectrum(queryParams.value);
      dataInfo.value = signalData.data;
      init(signalData.data);
    }
  },
);
</script>

<style scoped lang="scss">
.info {
  display: flex;
  flex-direction: column;
  text-align: center;
  div {
    margin-bottom: 10px;
  }
}

:deep(.ant-card-head-title) {
  padding-left: 10px;
  position: relative;
  &::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    transform: translateY(-45%);
    width: 3px;
    height: 16px;
    background-color: #0085ff;
  }
}
.modal_title {
  font-weight: 700;
  font-size: 17px;
}
</style>
